package Thread;

/**
 * @author liyang
 * @version 1.0
 * @package Thread
 * @file SyncDemo.java
 * @description
 * @time 2024-04-07 23:43
 */
public class SyncDemo {
    public static void main(String[] args) {
        Table table = new Table();
        Thread t1 = new Thread(){
            @Override
            public void run(){
                while(true){
                    int bean = table.getBean();
                    Thread.yield();
                    System.out.println(getName()+":"+bean);
                }
            }
        };
        Thread t2 = new Thread(){
            @Override
            public void run(){
                while(true){
                    int bean = table.getBean();
                    Thread.yield();
                    System.out.println(getName()+":"+bean);
                }
            }
        };
        t1.start();
        t2.start();
    }
}
class Table{
    private int beans=20;//桌子上有20个豆子
    /*synchronized方法实现同步，类似信号量机制*/
    public synchronized int getBean(){
        if(beans==0){
            throw new RuntimeException("没有豆子了!");
        }
        Thread.yield();//利用主动让出时间片来模拟执行到这里时线程时间片用完发生切换
        return beans--;
    }
}